package cn.jwcat.service.impl;

import cn.jwcat.dealEntity.DealStaff;
import cn.jwcat.entity.Password;
import cn.jwcat.entity.Role;
import cn.jwcat.entity.Staff;
import cn.jwcat.entity.StaffRole;
import cn.jwcat.mapper.StaffMapper;
import cn.jwcat.service.IStaffService;
import cn.jwcat.utils.MD5;
import cn.jwcat.utils.otherUtils;
import cn.jwcat.utils.result.Result;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 管理员 服务实现类
 * </p>
 *
 * @author 橙子味的猫
 * @since 2023-04-09
 */
@Transactional
@Service
public class StaffServiceImpl extends ServiceImpl<StaffMapper, Staff> implements IStaffService {

	@Override
	public Staff getStaffById(Integer id) {
		return this.getBaseMapper().selectById(id);
	}

	@Override
	public Staff updateStaff(Staff staff) {
		boolean remark = "".equals(staff.getRemark());
		boolean address = "".equals(staff.getAddress());
		boolean email = "".equals(staff.getEmail());
		boolean telephone = "".equals(staff.getTelephone());
		if (remark && address && email && telephone) return null;
		int i = this.getBaseMapper().updateStaff(staff);
		if (i != 1) return null;
		return this.getById(staff.getStaffId());
	}

	@Override
	public Result changePwd(Password password) throws Exception {
		Staff staff = this.baseMapper.selectById(password.getId());
		if (!MD5.getTrue(password.getOldPassword(), staff.getPassword())) {
			return Result.error().message("密码修改失败，请检查原始密码");
		}
		String newPassword = MD5.md5MinusSalt(password.getNewPassword());
		LambdaUpdateWrapper<Staff> staffWrapper = new LambdaUpdateWrapper<>();
		staffWrapper.set(Staff::getPassword, newPassword).eq(Staff::getStaffId, staff.getStaffId());
		boolean bool = this.update(staffWrapper);
		return otherUtils.dealBool(bool);
	}

	@Override
	public Boolean get(Integer staffId) {
		MPJLambdaWrapper<Staff> wrapper = new MPJLambdaWrapper<>();
		wrapper
			.selectAll(Staff.class)
			.select(Role::getRoleName)
			.leftJoin(StaffRole.class, StaffRole::getStaffId, Staff::getStaffId)
			.leftJoin(Role.class, Role::getRoleId, StaffRole::getRoleId)
			.eq(Staff::getStaffId, staffId);
		DealStaff dealStaff = this.getBaseMapper().selectJoinOne(DealStaff.class, wrapper);
		return "volunteer".equals(dealStaff.getRoleName());
	}
}
